<?php

/**
 * @Author: lujizhang
 * @Date:   2019-10-16 09:26:11
 * @Last Modified by:   lujizhang
 * @Last Modified time: 2019-11-04 13:47:15
 */
// https://developers.weixin.qq.com/doc/offiaccount/Intelligent_Interface/OCR.html

namespace app\api\model;
use think\Db;
use app\api\model\Wechat;

class WechatMedia extends Wechat{
    public $curImgFile;
    function __construct(){
        parent::__construct();
    }

    

    /**
     * 身份证ocr
     * @param  [type] $img_url [description]
     * @return [type]          [description]
     */
    public function getTmpMedia($media_id){
        
        $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?media_id='.$media_id.'&access_token='.$this->accessToken;
        var_dump($url);
        $res = $this->httpRequest($url,null,true);
        var_dump($res);
        die();
        $data = json_decode($res,true);
        if(isset($data['errcode']) && $data['errcode']===0){
            return $data;
        }
        else return false;      
    }

    public function saveMediaFromUrl($url){
        $image_content = file_get_contents($url);
        return $this->saveImg($image_content);
    }

    public function saveImg($image_content){
        $image_save_name = substr(md5($image_content),0,8).".jpg";
        $month = date("Y-m");
        $save_url =  DS . 'uploads' . DS . $month . DS . $image_save_name;
        $path = ROOT_PATH . 'public' . $save_url;
        
        $save_dir =dirname($path);
        if (!is_dir($save_dir) ) {
            mkdir($save_dir, 0755, true);
        }
        file_put_contents($path, $image_content);
        $this->curImgFile = $path;
        Db::table('sy_image')->insert(['url'=>$save_url]);
        $imgId = Db::table('sy_image')->getLastInsID();
        return $imgId;
    }

}